//
//  CHCoordinateManage.m
//  CHCoordinateSdk
//
//  Created by cyptt on 2022/7/19.
//

#import "CHCoordinateManage.h"
#import <CoreLocation/CoreLocation.h>
@interface CHCoordinateManage()<CLLocationManagerDelegate>
@property(nonatomic,strong)CLLocationManager * locationManager;
@property(nonatomic,strong)CLGeocoder * geoCoder;
//获取自身的经纬度坐标
@property (nonatomic, strong) CLLocation *myLocation;

@property(nonatomic,strong)void (^ locationInfoBlock)(CHLocationModel * locationModel);
@property(nonatomic,strong)void (^ failBlock)(NSError * error);
@property(nonatomic,assign)BOOL  isCoder;

@property(nonatomic,strong) CHLocationModel * locationModel;
@end

static CHCoordinateManage * _share;
@implementation CHCoordinateManage

+(CHCoordinateManage *)sharedInstance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _share = [[self alloc]init];
       
        [_share config];
    });
    return _share;
}

+(instancetype)allocWithZone:(struct _NSZone *)zone{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _share = [super allocWithZone:zone];
    });
    return _share;
}

- (id)copyWithZone:(nullable NSZone *)zone{
    return _share;
}

-(void)config{
   
}
-(void)startLocationIsCoder:(BOOL)isCoder locationInfoBlock:(void (^ __nullable)(CHLocationModel * locationModel))locationInfo failBlock:(void (^ __nullable)(NSError * error))failB{
    self.failBlock = failB;
    self.locationInfoBlock = locationInfo;
    self.isCoder = isCoder;
  

    //判断设备是否能够进行定位
    if ([CLLocationManager locationServicesEnabled]) {
        self.locationManager = [[CLLocationManager alloc]init];
        self.locationModel = [[CHLocationModel alloc]init];
        //地理信息
        self.geoCoder = [[CLGeocoder alloc] init];
        
        self.locationManager.delegate = self;
        //精确度获取到米
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        //设置过滤器为无
        self.locationManager.distanceFilter = kCLDistanceFilterNone;
        // 取得定位权限，有两个方法，取决于你的定位使用情况
        //一个是requestAlwaysAuthorization，一个是requestWhenInUseAuthorization
        [self.locationManager requestWhenInUseAuthorization];
        //开始获取定位
        [self.locationManager startUpdatingLocation];
    
     
    } else {
        NSLog(@"error");
        NSError * error = [[NSError alloc]initWithDomain:@"获取定位服务失败" code:3000 userInfo:nil];
        if (self.failBlock) {
            self.failBlock(error);
        }
    }
    
}

-(void)finishUpdate{
    [self.locationManager stopUpdatingLocation];
    self.locationManager = nil;

}

#pragma mark -- CLLocationManagerDelegate

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    NSLog(@"%lu", (unsigned long)locations.count);
    self.myLocation = locations.lastObject;
    NSLog(@"经度：%f 纬度：%f", _myLocation.coordinate.longitude, _myLocation.coordinate.latitude);
    
  
    self.locationModel.longitude = _myLocation.coordinate.longitude;
    self.locationModel.latitude =  _myLocation.coordinate.latitude;
    
    
    if (self.isCoder == NO) {
        if (self.locationInfoBlock) {
            self.locationInfoBlock(self.locationModel);
            [self finishUpdate];
        
        }
    }else{
        //    //通过坐标来推算该位置的相关信息
        [self.geoCoder reverseGeocodeLocation:self.myLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            if (placemarks.count > 0) {
                CLPlacemark *placemark = [placemarks objectAtIndex:0];
             
                
                // 位置名
                NSLog(@"sdk--name, %@", placemark.name);
                // 街道
                NSLog(@"sdk--thoroughfare, %@", placemark.thoroughfare);
                // 子街道
                NSLog(@"sdk--subThoroughfare, %@", placemark.subThoroughfare);
                // 市
                NSLog(@"sdk--locality, %@", placemark.locality);
                // 区
                NSLog(@"sdk--subLocality, %@", placemark.subLocality);
                // 国家
                NSLog(@"sdk--country, %@", placemark.country);
                
                //获取城市
                NSString *city = placemark.locality;
                if (!city) {
                    //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                    city = placemark.administrativeArea;
                }
                
                self.locationModel.name = placemark.name;
                self.locationModel.thoroughfare = placemark.thoroughfare;
                self.locationModel.subThoroughfare =  placemark.subThoroughfare;
                self.locationModel.locality =  placemark.locality;
                self.locationModel.subLocality =  placemark.subLocality;
                self.locationModel.country =  placemark.country;
                
                if (self.locationInfoBlock) {
            
                    self.locationInfoBlock(self.locationModel);
                    
                }
              
            } else if (error == nil && [placemarks count] == 0) {
                NSLog(@"No results were returned.");
                if (self.failBlock) {
                    self.failBlock(error);
                }
            } else if (error != nil) {
                NSLog(@"An error occurred = %@", error);
                if (self.failBlock) {
                    self.failBlock(error);
                }
            }
        }];
        //不用的时候关闭更新位置服务，不关闭的话这个 delegate 隔一定的时间间隔就会有回调
        [self finishUpdate];
    }

    
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
 
    NSLog(@"%d",[CLLocationManager locationServicesEnabled]);
 
    NSLog(@"%d",  [CLLocationManager authorizationStatus]);

    int status = [CLLocationManager authorizationStatus];
    if (status == 0){
        //kCLAuthorizationStatusNotDetermined
    }else{
        
        if (error) {
            [self finishUpdate];
            if (self.failBlock) {
                self.failBlock(error);
            }
        }
    }
   

}
@end
